package com.joyplus.report.business.service;

import com.alibaba.fastjson.JSON;
import com.joyplus.report.business.dao.MdCampaignSupplementDao;
import com.joyplus.report.business.document.C2sDistributionMachineStatisticsDocument;
import com.joyplus.report.business.document.C2sDistributionMachineStatisticsFreDocument;
import com.joyplus.report.business.document.C2sDistributionMachineStatisticsHourDocument;
import com.joyplus.report.business.document.C2sDistributionMachineStatisticsLocationDocument;
import com.joyplus.report.business.document.DistributionPvUvStatisticsDocument;
import com.joyplus.report.business.document.OptimizationTaskStatisticsDocument;
import com.joyplus.report.business.document.OptimizationTaskStatisticsFreDocument;
import com.joyplus.report.business.document.S2sDistributionMachineStatisticsDocument;
import com.joyplus.report.business.domain.C2sDistributionMachineStatisticsHour;
import com.joyplus.report.business.domain.StatisticsFre;
import com.joyplus.report.business.domain.PvUvModel;
import com.joyplus.report.business.domain.MdCampaignSupplement;
import com.joyplus.report.common.service.BaseService;
import com.mongodb.AggregationOutput;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.Fields;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * Service
 *
 * @author jeff
 * @date 2018-05-31
 */
@Service
@Transactional
public class S2SMdCampaignService extends
    BaseService<MdCampaignSupplementDao, MdCampaignSupplement> {

  @Resource
  private MdCampaignSupplementDao mdCampaignSupplementDao;

  @Autowired
  MongoTemplate mongoTemplate;


  @Override
  public List<MdCampaignSupplement> findAll() {
    return mdCampaignSupplementDao.findAll();
  }

  /**
   * C2S獲取實際投放的數據
   */
  public List getS2SRealCampaign(String[] id, String stratDate, String endDate) {
    List<DBObject> pipeline = new ArrayList();
    BasicDBObject groupAppend = new BasicDBObject("task_date", "$task_date")
        .append("campaign_id", "$campaign_id");
    BasicDBObject projectAppend = new BasicDBObject("task_date", "$_id.task_date")
        .append("campaign_id", "$_id.campaign_id")
        .append("pv", "$pv").append("_id", 0);
    BasicDBObject cond = new BasicDBObject("task_date",
        new BasicDBObject("$lte", endDate).append("$gte", stratDate));
    BasicDBObject cond1 = new BasicDBObject("campaign_id", new BasicDBObject("$in", id));
    BasicDBList dbList = new BasicDBList();
    dbList.add(cond);
    dbList.add(cond1);
    DBObject match = new BasicDBObject("$match", new BasicDBObject("$and", dbList));
    DBObject groupFields1 = new BasicDBObject("_id", groupAppend);
    groupFields1.put("pv", new BasicDBObject("$sum", "$pv"));
    DBObject group1 = new BasicDBObject("$group", groupFields1);
    DBObject project = new BasicDBObject("$project", projectAppend);
    DBObject sort = new BasicDBObject("$sort", new BasicDBObject("task_date",1));
    pipeline.add(match);
    pipeline.add(group1);
    pipeline.add(project);
    pipeline.add(sort);
    System.out.println(JSON.toJSONString(pipeline));
    AggregationOutput pvUvStatistics = mongoTemplate
        .getCollection("s2s_distribute_machine_statistics").aggregate(pipeline);
    Iterable<DBObject> results = pvUvStatistics.results();
    List<DBObject> collect = StreamSupport.stream(results.spliterator(), false)
        .collect(Collectors.toList());
    List<S2sDistributionMachineStatisticsDocument> statisticsDocument = (List<S2sDistributionMachineStatisticsDocument>) JSON
        .parseArray(JSON.toJSONString(collect), S2sDistributionMachineStatisticsDocument.class);
    HashMap<String, S2sDistributionMachineStatisticsDocument> map = new HashMap<>();
    S2sDistributionMachineStatisticsDocument taskStatisticsDocument = new S2sDistributionMachineStatisticsDocument();
    PvUvModel pvUvModel = new PvUvModel();
    List<PvUvModel> list = new ArrayList<>();
    for (S2sDistributionMachineStatisticsDocument doc : statisticsDocument
        ) {
      if (map.get(doc.getCampaignId()) == null) {
        MdCampaignSupplement byId = mdCampaignSupplementDao
            .getById(Integer.parseInt(doc.getCampaignId()));
        doc.setCampaignName(byId.getCampaignName());
        pvUvModel = new PvUvModel();
        pvUvModel.setTaskDate(doc.getTaskDate());
        pvUvModel.setPv((int)doc.getPv());
        list.add(pvUvModel);
        doc.setList(list);
        map.put(doc.getCampaignId(), doc);

      } else {
        taskStatisticsDocument = map.get(doc.getCampaignId());
        pvUvModel = new PvUvModel();
        pvUvModel.setTaskDate(doc.getTaskDate());
        pvUvModel.setPv((int)doc.getPv());
        taskStatisticsDocument.getList().add(pvUvModel);
        map.put(doc.getCampaignId(), taskStatisticsDocument);
      }
    }

    Iterator<Entry<String, S2sDistributionMachineStatisticsDocument>> iterator = map.entrySet()
        .iterator();
    statisticsDocument = new ArrayList<>();
    while (iterator.hasNext()) {
      statisticsDocument.add(iterator.next().getValue());
    }
    return statisticsDocument;


  }

  /**
   * C2S獲取實際投放小时
   */
  public List getS2SHour(String[] id, String stratDate, String endDate) {

    List<DBObject> pipeline = new ArrayList();
    BasicDBObject groupAppend = new BasicDBObject("task_hour", "$task_hour")
        .append("campaign_id", "$campaign_id").append("task_date","$task_date");
    BasicDBObject projectAppend = new BasicDBObject("task_hour", "$_id.task_hour")
        .append("campaign_id", "$_id.campaign_id").append("task_date","$_id.task_date")
        .append("pv", "$pv").append("_id", 0);
    BasicDBObject sortAppend = new BasicDBObject("task_hour", 1);
    BasicDBObject cond = new BasicDBObject("task_date",
        new BasicDBObject("$lte", endDate).append("$gte", stratDate));
    BasicDBObject cond1 = new BasicDBObject("campaign_id", new BasicDBObject("$in", id));
    BasicDBList dbList = new BasicDBList();
    dbList.add(cond);
    dbList.add(cond1);
    DBObject match = new BasicDBObject("$match", new BasicDBObject("$and", dbList));
    DBObject groupFields = new BasicDBObject("_id", groupAppend);
    groupFields.put("pv", new BasicDBObject("$sum", "$pv"));
    DBObject group = new BasicDBObject("$group", groupFields);
    DBObject project = new BasicDBObject("$project", projectAppend);
    DBObject sort = new BasicDBObject("$sort", sortAppend);
    pipeline.add(match);
    pipeline.add(group);
    pipeline.add(project);
    pipeline.add(sort);
    HashMap<String, S2sDistributionMachineStatisticsDocument> map = new HashMap<>();
    List<PvUvModel> PvUvModel = new ArrayList<>();
    PvUvModel pvUvModelBean = new PvUvModel();
    AggregationOutput pvUvStatistics = mongoTemplate
        .getCollection("s2s_distribute_machine_statistics").aggregate(pipeline);
    Iterable<DBObject> results = pvUvStatistics.results();

    Iterator<DBObject> iterator1 = results.iterator();
    while (iterator1.hasNext()) {
      DBObject next = iterator1.next();
      PvUvModel = new ArrayList<>();

      S2sDistributionMachineStatisticsDocument doc = new S2sDistributionMachineStatisticsDocument();
      doc.setCampaignId((String) next.get("campaign_id"));
      doc.setPv((int) (double) next.get("pv"));

      doc.setTaskDate((String) next.get("task_date"));
      doc.setTaskHour(next.get("task_hour").toString());
      if (map.get(doc.getCampaignId()+doc.getTaskDate()) == null) {
        MdCampaignSupplement byId = mdCampaignSupplementDao
            .getById(Integer.parseInt(doc.getCampaignId()));
        doc.setCampaignName(byId.getCampaignName());
        pvUvModelBean = new PvUvModel();
        pvUvModelBean.setPv((int) doc.getPv());
        pvUvModelBean.setTaskDate(doc.getTaskDate());
        pvUvModelBean.setTaskHour(Integer.parseInt(doc.getTaskHour()));
        PvUvModel.add(pvUvModelBean);
        doc.setList(PvUvModel);
        map.put(doc.getCampaignId()+doc.getTaskDate(), doc);
      } else {
        S2sDistributionMachineStatisticsDocument bean = map.get(doc.getCampaignId()+doc.getTaskDate());
        pvUvModelBean = new PvUvModel();
        pvUvModelBean.setPv((int) doc.getPv());
        pvUvModelBean.setTaskDate(doc.getTaskDate());
        pvUvModelBean.setTaskHour(Integer.parseInt(doc.getTaskHour()));
        bean.getList().add(pvUvModelBean);
        map.put(doc.getCampaignId()+doc.getTaskDate(), bean);
      }
    }
    List<S2sDistributionMachineStatisticsDocument> list = new ArrayList<>();
    Iterator<Entry<String, S2sDistributionMachineStatisticsDocument>> iterator = map
        .entrySet().iterator();
    while (iterator.hasNext()) {
      list.add(iterator.next().getValue());
    }
    return list;
  }

public List<MdCampaignSupplement> findS2SList(){
 return mdCampaignSupplementDao.findS2SList();
}


}
